package com.macro.mall.utils;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageZipUtil {
    public static File zipImageFile(File oldFile, int width, int height,
                                    float quality) {
        if (oldFile == null) {
            return null;
        }
        try {
            /** 对服务器上的临时文件进行处理 */

            Image srcFile = ImageIO.read(oldFile);
            System.out.println(oldFile);
            System.out.println(srcFile);
            Integer w = srcFile.getWidth(null);
            //  System.out.println(w);
            Integer h = srcFile.getHeight(null);
            //  System.out.println(h);
            double bili;
            if (width > 0) {
                bili = width / (double) w;
                height = (int) (h * bili);
            } else {
                if (height > 0) {
                    bili = height / (double) h;
                    width = (int) (w * bili);
                }
            }
            /** 宽,高设定 */
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
            //String filePrex = oldFile.getName().substring(0, oldFile.getName().indexOf('.'));
            /** 压缩后的文件名 */
            //newImage = filePrex + smallIcon+  oldFile.getName().substring(filePrex.length());

            /** 压缩之后临时存放位置 */
            FileOutputStream out = new FileOutputStream(oldFile);

            ImageIO.write(tag, "jpg", out);

            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return oldFile;
    }
}

